/*
 * Copyright (C) 2008
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.sca4idea.util;

import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiElement;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ResourceFileUtil;

/**
 * Utility class useful for resolving SCDL files.
 *
 * @author paul.jones
 */
public final class SCDLResolver {
    public static XmlFile loadScdlResource(PsiElement referencing, String scdlResource) {
        Module currentModule = ModuleUtil.findModuleForPsiElement(referencing);
        if (currentModule == null) {
            return null;
        }

        VirtualFile res = ResourceFileUtil.findResourceFileInScope(scdlResource, referencing.getManager().getProject(), currentModule.getModuleWithDependenciesAndLibrariesScope(false));
        if (res != null) {
            PsiFile fPsi = referencing.getManager().findFile(res);
            if (fPsi instanceof XmlFile) {
                return (XmlFile) fPsi;
            }
        }

        return null;
    }

    public static XmlFile loadScdlLocation(PsiElement referencing, String scdlLocation) {
        VirtualFile currentFile = getFileForElement(referencing);
        if (currentFile == null) {
            return null;
        }
        VirtualFile currentDir = currentFile.getParent();
        if (currentDir == null) {
            return null;
        }
        VirtualFile scdlFile = currentDir.findChild(scdlLocation);
        if (scdlFile == null) {
            return null;
        }

        PsiFile fPsi = referencing.getManager().findFile(scdlFile);
        if (fPsi instanceof XmlFile) {
            return (XmlFile) fPsi;
        }

        return null;
    }

    private static VirtualFile getFileForElement(PsiElement element) {
        PsiFile currentFile = element.getContainingFile();
        if (currentFile == null) {
            return null;
        }
        VirtualFile vf = currentFile.getVirtualFile();
        if (vf != null) {
            return vf;
        }

        PsiFile originalFile = currentFile.getOriginalFile();
        if (originalFile == null) {
            return null;
        }
        return originalFile.getVirtualFile();
    }
}
